package de.slothsoft.wasbinich.android;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import de.slothsoft.android.util.WebUtil;
import de.slothsoft.wasbinich.android.util.SvgUtil;

/**
 * An activity representing a list of Pictures. This activity has different
 * presentations for handset and tablet-size devices. On handsets, the activity
 * presents a list of items, which when touched, lead to a
 * {@link PictureDetailActivity} representing item details. On tablets, the
 * activity presents the list of items and item details side-by-side using two
 * vertical panes.
 * <p>
 * The activity makes heavy use of fragments. The list of items is a
 * {@link PictureListFragment} and the item details (if present) is a
 * {@link PictureDetailFragment}.
 * <p>
 * This activity also implements the required
 * {@link PictureListFragment.Callbacks} interface to listen for item
 * selections.
 */
public class PictureListActivity extends ActionBarActivity implements PictureListFragment.Callbacks {

    protected static final String URL_GUIDELINES = "http://wasbinich.slothsoft.de/legal-info/picture-guidelines"; //$NON-NLS-1$

    protected static final String PREF_GUIDELINES = "de.slothsoft.wasbinich.android.pictureGuidelines"; //$NON-NLS-1$

    /**
     * Whether or not the activity is in two-pane mode, i.e. running on a tablet
     * device.
     */
    private boolean mTwoPane;
    private PictureDetailFragment fragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_picture_list);

	if (findViewById(R.id.layout) != null) {
	    // The detail container view will be present only in the
	    // large-screen layouts (res/values-large and
	    // res/values-sw600dp). If this view is present, then the
	    // activity should be in two-pane mode.
	    this.mTwoPane = true;

	    // In two-pane mode, list items should be given the
	    // 'activated' state when touched.
	    ((PictureListFragment) getSupportFragmentManager().findFragmentById(R.id.picture_list))
		    .setActivateOnItemClick(true);
	}
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
	super.onWindowFocusChanged(hasFocus);
	View view = (View) ((View) findViewById(R.id.picture_list).getParent()).getParent();
	SvgUtil.setSvgToBackground(this, view, R.raw.background);
    }

    /**
     * Callback method from {@link PictureListFragment.Callbacks} indicating
     * that the item with the given ID was selected.
     */
    @Override
    public void onItemSelected(Long id) {
	if (this.mTwoPane) {
	    // In two-pane mode, show the detail view in this activity by
	    // adding or replacing the detail fragment using a
	    // fragment transaction.
	    Bundle arguments = new Bundle();
	    arguments.putLong(PictureDetailFragment.ARG_PICTURE_ID, id);
	    this.fragment = new PictureDetailFragment();
	    this.fragment.setArguments(arguments);
	    getSupportFragmentManager().beginTransaction().replace(R.id.layout, this.fragment).commit();

	} else {
	    // In single-pane mode, simply start the detail activity
	    // for the selected item ID.
	    Intent detailIntent = new Intent(this, PictureDetailActivity.class);
	    detailIntent.putExtra(PictureDetailFragment.ARG_PICTURE_ID, id);
	    startActivity(detailIntent);
	}
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
	getMenuInflater().inflate(R.menu.picture_list_menu, menu);
	return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

	final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
	boolean alreadyAccepted = prefs.getBoolean(PREF_GUIDELINES, false);
	if (!alreadyAccepted) {
	    showPictureGuidelines(item);
	    return true;
	}
	return doOnOptionsItemSelected(item);
    }

    public boolean doOnOptionsItemSelected(MenuItem item) {
	int itemId = item.getItemId();
	if (itemId == R.id.picture_list_new_picture) {
	    Intent pickPhoto = new Intent(Intent.ACTION_PICK,
		    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
	    startActivityForResult(pickPhoto, ActionCodes.SELECT_IMAGE);
	    return true;
	}
	if (itemId == R.id.picture_list_new_photo) {
	    PackageManager pm = getPackageManager();
	    if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)
		    || pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)) {
		Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(takePicture, ActionCodes.TAKE_PHOTO);
	    } else {
		Toast.makeText(getBaseContext(), R.string.picture_list_no_cam, Toast.LENGTH_SHORT).show();
	    }
	    return true;
	}
	return super.onOptionsItemSelected(item);
    }

    private void showPictureGuidelines(final MenuItem item) {
	AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle(R.string.main_guidelines_title)
		.setMessage(R.string.main_guidelines)
		.setPositiveButton(R.string.main_read_guidelines, new Dialog.OnClickListener() {

		    @Override
		    public void onClick(DialogInterface dialogInterface, int i) {
			WebUtil.openUrl(PictureListActivity.this, URL_GUIDELINES);
		    }
		}).setNegativeButton(R.string.facebook_ok, new Dialog.OnClickListener() {

		    @Override
		    public void onClick(DialogInterface dialogInterface, int i) {
			dialogInterface.dismiss();

			SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(
				PictureListActivity.this).edit();
			editor.putBoolean(PREF_GUIDELINES, true);
			editor.commit();

			doOnOptionsItemSelected(item);
		    }
		});
	builder.create().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
	super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
	if (this.fragment != null) {
	    this.fragment.onActivityResult(requestCode, resultCode, imageReturnedIntent);
	}
	if (resultCode != RESULT_OK)
	    return;

	switch (requestCode) {
	case ActionCodes.SELECT_IMAGE:
	case ActionCodes.TAKE_PHOTO:
	    Uri selectedImage = imageReturnedIntent.getData();
	    Intent detailIntent = new Intent(this, PictureDetailActivity.class);
	    detailIntent.putExtra(PictureDetailFragment.ARG_NEW_PICTURE_URL, selectedImage.toString());
	    startActivity(detailIntent);
	}
    }

    @Override
    public void onBackPressed() {
	NavUtils.navigateUpFromSameTask(this);
    }
}
